<template>
  <div style="width:90%;">
    <el-form :model="planForm" :rules="planRules" ref="planForm" label-width="150px">
      <el-button @click="goback()" size="mini" type="primary" style="margin-left:1000px">返回</el-button>
      <el-input v-model="planForm.uuid" type="hidden"></el-input>
      <el-input v-model="planForm.orgSeq" type="hidden"></el-input>
      <el-form-item label="奖品类型" prop="prizeType">
        <el-select v-model="planForm.prizeType">
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="奖品名称：" prop="prizeName" v-if="planForm.prizeType == '2'">
        <el-input
          v-model="planForm.prizeName"
          :disabled="disabledFlag"
          style="width:360px;"
          placeholder="请输入奖品名称"
          maxlength="30"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="奖品描述：" prop="prizeInfo">
        <el-input
          type="textarea"
          v-model="planForm.prizeInfo"
          :disabled="disabledFlag"
          placeholder="请输入奖品说明"
          maxlength="120"
          show-word-limit
          :autosize="{minRows:2}"
          style="width:650px;"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item label="开始时间：" prop="beginTime">
        <el-date-picker
          v-model="planForm.beginTime"
          type="date"
          placeholder="请选择开始时间"
          value-format="yyyy-MM-dd"
          :disabled="disabledFlag"
          style="width:325px;"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间：" prop="endTime">
        <el-date-picker
          v-model="planForm.endTime"
          type="date"
          placeholder="请选择结束时间"
          value-format="yyyy-MM-dd"
          :disabled="disabledFlag"
          style="width:325px;"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="发布状态：">
        <el-radio-group v-model="planForm.status" :disabled="disabledFlag">
          <el-radio-button label="0">不发布</el-radio-button>
          <el-radio-button label="1">发布</el-radio-button>
        </el-radio-group>
      </el-form-item>-->

      <el-form-item label="优惠券：" prop="planCouponList" v-if="planForm.prizeType =='1'">
        <el-table
          :data="planCouponList"
          @selection-change="planCouponChecked"
          border
          style="font-size: 10px;width:70%;"
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        >
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column
            prop="couponName"
            label="优惠券名称"
            width="200"
            header-align="center"
         
          ></el-table-column>
          <el-table-column prop="couponSeq" label="优惠券编号" width="150" header-align="center"></el-table-column>
          <el-table-column
            prop="couponMoney"
            label="优惠券面值"
            width="150"
            header-align="center"
            align="left"
          >
            <template slot-scope="scope">
              <span>满{{scope.row.conponLimitMoney}}减{{scope.row.couponMoney}}元</span>
            </template>
          </el-table-column>
          <el-table-column prop="comments" label="使用说明" header-align="center"></el-table-column>
        </el-table>
        <div style="margin-top:10px;">
          <el-button type="primary" @click="selectCoupon('planForm')" v-if="!disabledFlag">选择卡券</el-button>
          <!-- <el-button @click="deleteCoupon('planForm')" v-if="!disabledFlag">删除卡券</el-button> -->
        </div>
      </el-form-item>

      <el-form-item label="奖品图片:" prop="imgListone" v-if="planForm.prizeType =='2'">
        <image-upload v-model="planForm.imgListone" :size="'400x400'" :limit="1"></image-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('planForm')" v-if="!disabledFlag">保 存</el-button>
        <el-button @click="resetForm('planForm')">取 消</el-button>
      </el-form-item>
    </el-form>

    <el-dialog title="选择优惠券" :visible.sync="dialogVisibleCoupon" width="55%">
      <el-form
        :inline="true"
        :model="formCoupon"
        class="search-form-inline"
        style="margin-top:-20px;"
      >
        <el-input v-model="formCoupon.couponName" style="width:200px;" placeholder="优惠券名称"></el-input>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="getCouponList()">查询</el-button>
      </el-form>
      <el-table
        ref="singleTable"
        :data="couponList"
        @selection-change="couponChecked"
        border
        style="font-size: 10px;width:100%;"
        height="300"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column
          prop="couponName"
          label="优惠券名称"
          width="200"
          header-align="center"
    
        ></el-table-column>
        <el-table-column prop="couponSeq" label="优惠券编号" width="150" header-align="center"></el-table-column>
        <el-table-column prop="couponMoney" label="优惠券面值" width="150" header-align="center">
          <template slot-scope="scope">
            <span>满{{scope.row.conponLimitMoney}}减{{scope.row.couponMoney}}元</span>
          </template>
        </el-table-column>
        <el-table-column prop="comments" label="使用说明" header-align="center"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleCoupon = false">取 消</el-button>
        <el-button
          type="primary"
          @click="couponConfirm()"
          :disabled="this.lsCouponList.length!=1"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { addPrize, updatePrize, queryGenCoupon } from "@/api/prizeLibrary";
import {
  queryPromotionList,
  queryPromotionById,
  queryCouponById,
  savePromotion,
  updatePromotionStatus,
  createTPlan
} from "@/api/promotionProgramEdit";
import imageUpload from "@/page/common/Image-upload";
import { queryCouponList } from "@/api/promotionProgramEdit";

export default {
  data() {
    return {
      logininfo: {},
      orgList: [],
      orgSeq: "",
      loading: true,
      typeOptions: [
        { value: "1", label: "虚拟奖品" },
        { value: "2", label: "实物奖品" }
      ],
      lsPlanCouponList: [],
      lsCouponList: [],
      planCouponList: [],
      couponList: [],
      planForm: {
        uuid: "",
        prizeType: "2",
        prizeName: "",
        prizeInfo: "",
        beginTime: "",
        endTime: "",
        status: "",
        promotionCouponInfo: [],
        imgListone: [],
        prizePicture: "",
        couponId: ""
      },
      formCoupon: {
        couponName: ""
      },
      dialogVisibleCoupon: false,
      disabledFlag: false,
      listQuery: {
        current: 1,
        size: 10
      },
      total: 0,
      planRules: {
        /*
        prizeName: [{ required: true, message: "请输入奖品名称", trigger: "blur" }],
        beginTime: [{ required: true, message: "请选择开始时间", trigger: "blur" }],
        endTime: [{ required: true, message: "请选择结束时间", trigger: "blur" }]
        */
      }
    };
  },
  components: {
    imageUpload
  },
  mounted() {
    this.logininfo = localStorage.getItem("logininfo");
    this.orgList = JSON.parse(this.logininfo).orgList;
    this.orgSeq = this.orgList[0].orgSeq;
    this.planForm.orgSeq = this.orgList[0].orgSeq;

    var v = this.$route.params.edit;
    if (v) {
      // 修改，回显值
      this.planForm.uuid = v.uuid;
      this.planForm.prizeName = v.prizeName;
      this.planForm.prizeType = String(v.prizeType);
      this.planForm.prizePicture = v.prizePicture;
      this.planForm.couponId = v.couponId;
      // this.planCouponList = res.result.promotionCouponInfo;
      this.planForm.imgListone =
        v.prizePicture == null || v.prizePicture == "" ? [] : [v.prizePicture];
      this.planForm.prizeInfo = v.prizeInfo;
      this.planForm.beginTime = v.beginTime;
      this.planForm.endTime = v.endTime;
      this.planForm.status = v.status;

      this.queryPromotionById(v.couponId);
    } else {
      // 新增，默认值
      this.planForm.uuid = "";
      this.planForm.status = "1";
      this.getCouponList();
    }
  },
  methods: {
    goback() {
      this.$router.go("-1");
    },
    quantityBlur(e, idx) {
      if (e.target.value == "") {
        return;
      }
      let flag = new RegExp("^[1-9][0-9]*$").test(e.target.value);
      if (!flag) {
        this.$message({
          message: "限领数量请输入正整数",
          type: "warning"
        });
        e.target.value = "";
      }
    },
    numberBlur(e, name) {
      if (e.target.value == "") {
        return;
      }
      let flag = new RegExp("^[1-9][0-9]*$").test(e.target.value);
      if (!flag) {
        this.$message({
          message: name + "请输入正整数",
          type: "warning"
        });
        e.target.value = "";
      }
    },
    queryPromotionById(uuid) {
       ;
      let data = {
        size: 100,
        current: 1,
        condition: {},
        ascs: [],
        descs: []
      };
      queryGenCoupon(data).then(res => {
        if (res.records != null && res.records.length > 0) {
          // this.planCouponList =res.records;
          // 去掉已选的
          for (var i in res.records) {
            console.log(uuid);
            console.log(res.records[i]);
            if (uuid == res.records[i].uuid) {
              this.planCouponList.push(res.records[i]);
            }
          }
        }
        this.getCouponList();
      });
      this.loading = false;
    },

    getCouponList() {
      let data = {
        size: 100,
        current: 1,
        condition: {
          status: 1,
          couponType: 1,
          keyWord: this.formCoupon.couponName
        },
        ascs: [],
        descs: []
      };
      queryGenCoupon(data).then(res => {
        this.couponList = res.records;
        // 去掉已选的
        for (var i in this.planCouponList) {
          this.removeByValue(
            this.couponList,
            "uuid",
            this.planCouponList[i].uuid
          );
        }
      });
      this.loading = false;
    },

    planCouponChecked(row) {
      this.lsPlanCouponList = row;
    },
    couponChecked(row) {
      this.lsCouponList = row;
      if (this.lsCouponList.length > 1) {
        this.$refs.singleTable.toggleRowSelection(this.lsCouponList[0]);
      }
    },
    selectCoupon() {
      // 显示选择卡券对话框
      this.dialogVisibleCoupon = !this.dialogVisibleCoupon;
    },
    deleteCoupon() {
      // 删除已选择的卡券
      this.couponList = this.couponList.concat(this.lsPlanCouponList);
      for (var i in this.lsPlanCouponList) {
        this.removeByValue(
          this.planCouponList,
          "uuid",
          this.lsPlanCouponList[i].uuid
        );
      }
    },
    couponConfirm() {
      this.dialogVisibleCoupon = !this.dialogVisibleCoupon;
      this.planCouponList = this.lsCouponList; //this.planCouponList.concat(this.lsCouponList);
      // for (var i in this.lsCouponList) {
      //   this.removeByValue(this.couponList, "uuid", this.lsCouponList[i].uuid);
      // }
    },

    submitForm(formName) {
      // 保存奖品
      if (this.planForm.prizeType == "2") {
        if (this.planForm.prizeName == "" || this.planForm.prizeName == null) {
          this.$message.error("请输入奖品名称");
          return;
        }
      }
      if (
        this.planForm.prizeType == "2" &&
        this.planForm.imgListone.length == 0
      ) {
        this.$message.error("请上传图片");
        return;
      }
      if (this.planForm.prizeType == "1" && this.planCouponList.length != 1) {
        this.$message.error("请选择1张卡券,多余的请删除");
        return;
      }
      for (var i in this.planCouponList) {
         ;
        // 删除提交时不需要的属性或容易导致错误的属性
        if (
          this.planCouponList[i].couponId != null &&
          this.planCouponList[i].couponId != undefined
        ) {
          this.planCouponList[i].couponId = this.planCouponList[i].uuid;
        }
        delete this.planCouponList[i].createTime;
        delete this.planCouponList[i].createUser;
        delete this.planCouponList[i].updateTime;
        delete this.planCouponList[i].updateUser;
        delete this.planCouponList[i].beginTime;
        delete this.planCouponList[i].endTime;
        delete this.planCouponList[i].comments;
        delete this.planCouponList[i].validCreateDate;
        delete this.planCouponList[i].validEndDate;
      }
      // this.planForm.beginTime = this.planForm.beginTime.substring(0, 10);
      // this.planForm.endTime = this.planForm.endTime.substring(0, 10);
      this.planForm.promotionCouponInfo = this.planCouponList;
      if (this.planForm.prizeType == "1") {
        this.planForm.couponId = this.planForm.promotionCouponInfo[0].uuid;
      }
      if (this.planForm.prizeType == "2") {
        this.planForm.prizePicture = this.planForm.imgListone[0];
      }

      console.log(this.planForm);
      if (this.planForm.uuid == "") {
        addPrize(this.planForm).then(res => {
          if (res.code == "1") {
            this.$message({
              showClose: true,
              message: "保存成功",
              type: "success"
            });
            this.$router.push("prizeLibrary");
          } else {
            this.$message({
              showClose: true,
              message: "保存失败",
              type: "success"
            });
          }
        });
      } else {
        updatePrize(this.planForm).then(res => {
          if (res.code == "1") {
            this.$message({
              showClose: true,
              message: "修改成功",
              type: "success"
            });
            this.$router.push("prizeLibrary");
          } else {
            this.$message({
              showClose: true,
              message: "修改失败",
              type: "success"
            });
          }
        });
      }
    },
    // 数组，属性，属性值
    removeByValue: function(arr, attr, value) {
      if (arr == null) {
        return;
      }
      var index = 0;
      for (var i in arr) {
        if (arr[i][attr] == value) {
          index = i;
          break;
        }
      }
      arr.splice(index, 1);
    },
    handleRemove(file, fileList) {
      let newfileList = [];
      fileList.forEach((item, i) => {
        let data = {
          name: item.name,
          url: item.url
        };
        newfileList.push(data);
      });
      this.fileList = newfileList;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$router.push("prizeLibrary");
    }
  }
};
</script>
<style lang="less" scoped>
.el-col-20 {
  border: 1px solid #ebeef5;
  margin-left: 150px;
  width: 60%;
}
.el-input {
  width: 60%;
}
.search-form-inline {
  border: 1px solid #ebeef5;
  line-height: 30px;
  padding: 12px;
  margin-bottom: 5px;
}
thead {
  .el-table-column--selection {
    .cell {
      display: none;
    }
  }
}
</style>